<template>
  <Popup
    v-model:visible="popupVisible"
    :drag-enabled="false"
    :close-on-outside-click="false"
    :show-close-button="true"
    :show-title="true"
    :width="1200"
    :height="850"
    max-width="95vw"
    max-height="95vh"
    @hidden="hidden"
    @isReady="isReady"
    title="编辑药品"
  >
    <DxScrollView width="100%" height="100%" style="padding-bottom: 30px">
      <DxForm
        id="form"
        label-location="left"
        :col-count="2"
        :form-data="drugModel"
        @initialized="saveFormInstance"
        :validation-group="drugValidation"
      >
        <DxGroupItem>
          <DxGroupItem caption="类别编码信息">
            <DxSimpleItem
              data-field="drugSortId"
              editorType="dxSelectBox"
              :editor-options="
                getSelectBoxOptions({
                  displayExpr: 'name',
                  valueExpr: 'drugSortId',
                  dataSource: drugSorts,
                })
              "
            >
              <DxLabel text="药品分类" />
            </DxSimpleItem>
            <DxSimpleItem data-field="coding" :editor-options="editOptions">
              <DxLabel text="药品编码" />
            </DxSimpleItem>
            <DxSimpleItem
              data-field="isDanger"
              editorType="dxSelectBox"
              :editor-options="
                getDicSelectBoxOptions({
                  dataSource: dicDangers,
                })
              "
            >
              <DxLabel text="毒理分类" />
            </DxSimpleItem>
          </DxGroupItem>
          <DxGroupItem caption="药品名称信息">
            <DxSimpleItem data-field="name" :editor-options="getSimpleSuffixS()">
              <DxLabel text="药品名称" />
            </DxSimpleItem>
            <DxGroupItem :col-count="2">
              <DxSimpleItem
                data-field="pinyin"
                :editor-options="getSimpleSuffix('拼音')"
              >
                <DxLabel text="药品简码" />
              </DxSimpleItem>
              <DxSimpleItem
                data-field="wubi"
                :editor-options="getSimpleSuffix('五笔')"
              >
              </DxSimpleItem>
            </DxGroupItem>
            <DxSimpleItem
              data-field="englishName"
              :editor-options="editOptions"
            >
              <DxLabel text="英文名称" />
            </DxSimpleItem>
          </DxGroupItem>
          <DxGroupItem caption="药品其他别名">
            <DxSimpleItem>
              <DxDataGrid
                :data-source="drugModel.drugAliasList"
                :remote-operations="false"
                :allow-column-reordering="true"
                :row-alternation-enabled="true"
                :show-borders="true"
              >
                <DxEditing
                  :allow-updating="true"
                  :allow-deleting="true"
                  :allow-adding="true"
                  mode="row"
                />
                <DxColumn data-field="name" caption="药品名称" />
                <DxColumn data-field="pinyin" caption="拼音简码" />
                <DxColumn data-field="wubi" caption="五笔简码" />
              </DxDataGrid>
            </DxSimpleItem>
          </DxGroupItem>
        </DxGroupItem>
        <DxGroupItem>
          <DxGroupItem caption="药品参数信息" :col-count="2">
            <DxSimpleItem
              data-field="dosage"
              editorType="dxSelectBox"
              :editor-options="
                getDicSelectBoxOptions({
                  dataSource: dicDosage,
                })
              "
            >
              <DxLabel text="药品剂型" />
            </DxSimpleItem>
            <DxSimpleItem
              data-field="dosageUnit"
              editorType="dxSelectBox"
              :editor-options="
                getDicSelectBoxOptions({
                  dataSource: dicUnit,
                })
              "
            >
              <DxLabel text="剂量单位" />
            </DxSimpleItem>
            <DxSimpleItem
              data-field="prescriptionCategory"
              editorType="dxSelectBox"
              :editor-options="
                getDicSelectBoxOptions({
                  dataSource: dicCategory,
                })
              "
            >
              <DxLabel text="处方药品" />
            </DxSimpleItem>
            <DxSimpleItem
              data-field="prescriptionLimit"
              :editor-options="editOptions"
            >
              <DxLabel text="处方限量" />
            </DxSimpleItem>
            <DxSimpleItem
              data-field="valueClassification"
              editorType="dxSelectBox"
              :editor-options="
                getDicSelectBoxOptions({
                  dataSource: dicValueClassification,
                })
              "
            >
              <DxLabel text="价值分类" />
            </DxSimpleItem>
            <DxSimpleItem
              data-field="supply"
              editorType="dxSelectBox"
              :editor-options="
                getDicSelectBoxOptions({
                  dataSource: dicSupply,
                })
              "
            >
              <DxLabel text="货源情况" />
            </DxSimpleItem>
            <DxSimpleItem
              data-field="medicationEchelon"
              editorType="dxSelectBox"
              :editor-options="
                getDicSelectBoxOptions({
                  dataSource: dicEchelon,
                })
              "
            >
              <DxLabel text="用药梯次" />
            </DxSimpleItem>
          </DxGroupItem>
          <DxGroupItem caption="药品限制信息" :col-count="2">
            <DxSimpleItem
              data-field="prescriptionPosition"
              editorType="dxSelectBox"
              :editor-options="
                getDicSelectBoxOptions({
                  dataSource: dicPosition,
                })
              "
            >
              <DxLabel text="处方职务" />
            </DxSimpleItem>
            <DxSimpleItem
              data-field="medicalPosition"
              editorType="dxSelectBox"
              :editor-options="
                getDicSelectBoxOptions({
                  dataSource: dicEchelon,
                })
              "
            >
              <DxLabel text="医保职务" />
            </DxSimpleItem>
            <DxSimpleItem
              data-field="sex"
              editorType="dxSelectBox"
              :editor-options="
                getDicSelectBoxOptions({
                  dataSource: dicSex,
                })
              "
            >
              <DxLabel text="适用性别" />
            </DxSimpleItem>
          </DxGroupItem>
          <DxGroupItem caption="药品性质设定" :col-count="1">
            <DxSimpleItem>
                <DxCheckBox
                  :width="100"
                  text="单位药"
                  v-model:value="drugModel.isUnitDrug"
                />
            </DxSimpleItem>
            <DxSimpleItem>
              <div class="align-center">
                <DxCheckBox
                  :width="100"
                  text="原料药"
                  v-model:value="drugModel.medicalMaterial"
                />
                <DxSelectBox
                  style="flex: 1"
                  v-bind="
                    getDicSelectBoxOptions({
                      dataSource: dicMedicalMaterialSort,
                    })
                  "
                  placeholder="可以进处方"
                  v-model:value="drugModel.drugDrugMedicalMaterialSort"
                  :disabled="isMaterialSort"
                />
              </div>
            </DxSimpleItem>
          </DxGroupItem>
            
        </DxGroupItem>
      </DxForm>
    </DxScrollView>
    <div class="lb-form-button-right">
      <DxButton
        text="取消"
        styling-mode="text"
        type="default"
        @click="hidden()"
      />

      <DxButton
        text="保存并继续添加"
        styling-mode="text"
        type="default"
        @click="save(false)"
      />

      <DxButton
        text="保存并退出"
        styling-mode="text"
        type="default"
        @click="save(true)"
      />
    </div>
  </Popup>
</template>

<script lang="ts">
import { DxPopup } from "devextreme-vue/popup";
import Popup from "@/framework/components/popup/popup.vue";
import {
  DxForm,
  DxSimpleItem,
  DxGroupItem,
  DxTabbedItem,
  DxTabPanelOptions,
  DxTab,
  DxRequiredRule,
  DxLabel,
} from "devextreme-vue/form";
import {PublicClient} from "@/api/api_publicclient";
import DxTagBox from "devextreme-vue/tag-box";
import DxCheckBox from "devextreme-vue/check-box";
import { ElButton, ElTable, ElTableColumn } from "element-plus";
import { Vue, Options, Prop, Watch, Inject } from "vue-property-decorator";
import { DxScrollView } from "devextreme-vue/scroll-view";
import { DxColumn, DxDataGrid, DxEditing } from "devextreme-vue/data-grid";
import DataSource from "devextreme/data/data_source";
import DxButton from "devextreme-vue/button";
import { dxSelectBoxOptions } from "node_modules/devextreme/ui/select_box";
import {
  DictionaryItemModel,
  DictionaryOutput,
  DrugSortInfoVO,
  // DrugSubmitDTO
} from "@/api/api_dictionaryclient";
import { InputInsertForDrugModel as DrugModelI} from "@/api/api_drugclient";
import { ApiTool } from "@/api/api-tool";
import { DxSelectBox } from "devextreme-vue/select-box";
import { DrugSortClient } from "@/api/api_drugsortclient";
import * as fieldConstName from "@/config/field-const-name";
import { DictionaryUtil } from "@/utils/dictionary-util";
import { DrugClient } from "@/api/api_drugclient";
import DrugData from "@/data-source/drug";
import notify from "devextreme/ui/notify";
let self:CreateDrugZh
interface InputInsertForDrugModel extends DrugModelI{
  pinyin?: string | undefined;
  wubi?: string | undefined;
}
@Options({
  components: {
    Popup,
    DxForm,
    DxSimpleItem,
    DxGroupItem,
    DxTabbedItem,
    DxTabPanelOptions,
    DxTab,
    DxRequiredRule,
    DxLabel,
    DxTagBox,
    DxCheckBox,
    ElButton,
    ElTable,
    ElTableColumn,
    DxScrollView,
    DxColumn,
    DxDataGrid,
    DxEditing,
    DxButton,
    DxSelectBox,
  },
})
export default class CreateDrugZh extends Vue {
  created () {
    self = this
  }
  
  @Prop({ type: Boolean, default: false })
  value!: boolean;

  @Prop({ type: String, default: "" })
  drugId: string;

  // 目录id
  get drugSortId() {
    return (this.$route.query.drugSortId || "") as string;
  }
  // 方案id
  get drugSchemeId() {
    return (this.$route.query.drugSchemeId || "") as string;
  }
  // 父目录id
  get parentId() {
    return (this.$route.query.parentId || "") as string;
  }
  drugData: DrugData;
  drugValidation = {};
  drugModel: InputInsertForDrugModel = {
    skinTest: false,
    firstAidMedicine: false,

    newDrug: false,
    isLongMedicalAdvice: false,
    antibacterialDrugs: false,
    medicalMaterial: false,
    drugAliasList: [],
 isUnitDrug:false
  };
  drugModelBase: InputInsertForDrugModel = {
    skinTest: false,
    firstAidMedicine: false,
    newDrug: false,
    isLongMedicalAdvice: false,
    antibacterialDrugs: false,
    medicalMaterial: false,
    drugAliasList: [],
    isUnitDrug:false
  };

  editOptions = {
    stylingMode: "outlined",
    placeholder: "请输入",
  };
  isMaterialSort = true
  @Watch("drugModel.medicalMaterial")
  changeIsMaterialSort () {
    if(this.drugModel)
    this.isMaterialSort = !this.isMaterialSort
  }
  getDicSelectBoxOptions(extendOptions: dxSelectBoxOptions) {
    return Object.assign(
      {},
      this.getSelectBoxOptions({
        displayExpr: "displayValue",
        valueExpr: "dictionaryId",
      }),
      extendOptions
    );
  }

  getSelectBoxOptions(extendOptions: dxSelectBoxOptions): dxSelectBoxOptions {
    return Object.assign({}, this.tagSetting, extendOptions);
  }

  tagSetting: dxSelectBoxOptions = {
    stylingMode: "outlined",
    showDropDownButton: true,
  };

  popupVisible = this.value || false;

  @Inject()
  apiTool: ApiTool; ///表单验证

  dictionaryUtil: DictionaryUtil;

  //表单组件
  dataFormInstance = null;

  //表单初始化
  saveFormInstance(e) {
    this.dataFormInstance = e.component;
  }

  drugSorts: DrugSortInfoVO[] = []; // 毒理分类

  mounted() {
    this.dictionaryUtil = new DictionaryUtil(this.apiTool);
    let client = this.apiTool.createClient(DrugClient);
    this.drugData = new DrugData(client, this);
    // this.fetchData();
  }

  dictionaryList: DictionaryItemModel = {};
  // 弹窗弹出完成
  async isReady() {
    let info = await this.drugData.info(this.drugId, this.drugSchemeId);
    this.dictionaryList = info.dictionaryList || {};
    info.dictionaryList = undefined;
    this.drugModel = info;
    this.getDrugSort();
  }
  getPinYinCodeAndWubiCode () {
    let client = this.apiTool.createClient(PublicClient)
    client.getPinYinForWuBi(this.drugModel.name).then((res)=>{
      this.drugModel.pinyin = res.data.pinYinCode
      this.drugModel.wubi = res.data.wubiCode
      this.drugModel = {...this.drugModel}
    })
  }
  getSimpleSuffixS(text: string): dxSelectBoxOptions {
    return {
      stylingMode: "outlined",
      buttons: [
        {
          name: "unit",
          location: "after",
          options: {
            text: text,
            stylingMode: "text",
          },
        },
      ],onChange(e) {
        self.getPinYinCodeAndWubiCode()
      }
    };
  }
  async getDrugSort() {
    let client = this.apiTool.createClient(DrugSortClient);
    let result = await client.page({
      pageInfo: {
        pageSize: 100,
      },
    });
    this.drugSorts = result.listData;
  }

  // 高危药品
  get dicDangers() {
    return this.dictionaryList.drugDrugToxicologyType || [];
  }

  // 剂型
  get dicDosage() {
    return this.dictionaryList.drugDrugDosage || [];
  }

  // 处方类别
  get dicCategory() {
    return this.dictionaryList.drugDrugPrescriptionDrug || [];
  }

  // 剂量单位
  get dicUnit() {
    return this.dictionaryList.drugDrugDosageUnit || [];
  }

  // 价值分类
  get dicValueClassification() {
    return this.dictionaryList.drugDrugValueClassification || [];
  }

  // 货源情况
  get dicSupply() {
    return this.dictionaryList.drugDrugSupply || [];
  }

  // 用药梯次
  get dicEchelon() {
    return this.dictionaryList.drugDrugMedicationEchelon || [];
  }

  // 处方职务
  get dicPosition() {
    return this.dictionaryList.drugDrugSkinTestSort || [];
  }

  // 皮试类别
  get dicSkinTestSort() {
    return this.dictionaryList.drugDrugMedicalPosition || [];
  }

  // 适用性别
  get dicSex() {
    return this.dictionaryList.drugDrugSex || [];
  }


  // 原料药
  get dicMedicalMaterialSort() {
    return this.dictionaryList.drugDrugMedicalMaterialSort || [];
  }

  getSimpleSuffix(text: string): dxSelectBoxOptions {
    return {
      stylingMode: "outlined",
      buttons: [
        {
          name: "unit",
          location: "after",
          options: {
            text: text,
            stylingMode: "text",
          },
        },
      ],
      disabled:true
    };
  }

  @Watch("value")
  watchValue() {
    this.popupVisible = this.value;
  }

  hidden() {
    this.popupVisible = false;
    this.$emit("update:value", this.popupVisible);
  }

  ///表单验证
  formValidate() {
    const validate = this.dataFormInstance.validate();
    return validate;
  }

  async save(isClose: boolean) {
    let validate = this.formValidate();
    this.drugModel.schemeId = this.drugSchemeId;
    let client = this.apiTool.createClient(DrugClient);
    await client
      .submit(this.drugModel)
      .then(() => {
        notify("保存成功", "success", 2000);
        if (isClose) this.hidden();
        this.$emit("success");
        this.drugModel = {
          skinTest: false,
          firstAidMedicine: false,
          newDrug: false,
          isLongMedicalAdvice: false,
          antibacterialDrugs: false,
          medicalMaterial: false,
          drugAliasList: [],
          isUnitDrug:false
        };
      })
      .catch((e) => {
        notify(e, "error", 2000);
      });
  }
}
</script>
